package demo.config.login;

import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义模式
 * @author : Windy
 * @version :1.0
 * @since : 2020/12/28 15:47
 */
public class AccountGranter extends AbstractTokenGranter {

    //模式名称
    public static final String GRANT_TYPE = "account_mobile";
    private final AuthenticationManager authenticationManager;

    public  AccountGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        //此处map为controller封装的参数map，名字也可以自己定义
        //从参数中获取手机号
        String mobile = parameters.get("username");
        //参数中获取密码
        String password = parameters.get("password");
        //参数中获取密码
        String vcode = parameters.get("vcode");

        //删除参数中的两项(这里我暂时还不清楚为啥要删除，不清楚这个传输会引起什么问题，源码中删除那么我先暂时删除)
        parameters.remove("password");
        parameters.remove("vcode");

        //暂时将三个全部传入
        Authentication userAuth = new AccountLoginToken(mobile, password,vcode);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

        try {
            userAuth = authenticationManager.authenticate(userAuth);
        }catch (AccountStatusException | BadCredentialsException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        }
        // If the username/password are wrong the spec says we should send 400/invalid grant
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("校验失败: " + mobile);
        }

        //验证通过，则返回一个Oauth2token。
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
